package sys

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"seawolf-admin-go/internal/app/admin/controller"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/internal/routers"
	"seawolf-admin-go/internal/service/RoleService"
	"seawolf-admin-go/utility/response"
)

type cRole struct {
	*controller.BaseController
}

func NewRoleController(group *ghttp.RouterGroup, defaultVersion string) {
	// 初始化内部变量
	inputReq := &BaseReq.I{}
	c := &cRole{&controller.BaseController{Req: inputReq}}
	c.New(group, defaultVersion)
}

func (c *cRole) New(group *ghttp.RouterGroup, defaultVersion string) {
	isOrg := 0
	// 配置表名
	c.Req = &BaseReq.I{
		TableName:          "sys_role",
		InfoIgnoreProperty: "delete_at",
		SoftDeleteField:    "delete_at",
		ListQueryOp: &BaseReq.QueryOp{
			OtherWhere: func(r *ghttp.Request) g.Map {
				return g.Map{
					"is_org": isOrg,
				}
			},
		},
		PageQueryOp: &BaseReq.QueryOp{
			KeyWordLikeFields: []string{
				"name",
				"label",
			},
			OtherWhere: func(r *ghttp.Request) g.Map {
				return g.Map{
					"is_org": isOrg,
				}
			},
		},
		InfoQueryOp: &BaseReq.QueryOp{
			OtherWhere: func(r *ghttp.Request) g.Map {
				return g.Map{
					"is_org": isOrg,
				}
			},
		},
		AddBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
			data["is_org"] = isOrg
			return response.SuccessByRequest(r)
		},
		UpdateBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
			data["is_org"] = isOrg
			return response.SuccessByRequest(r)
		},
	}
	// 登录中间件
	// 权限判断中间件
	// 处理初始化方法和结束方法中间件
	group.Middleware(func(r *ghttp.Request) {
		c.Init(r)
		r.Middleware.Next()
		c.Shut(r)
	})
	// 注册基础路由
	controller.RegBase(group, c, nil)

	// 属于 组织人员 的角色
	group.POST("/listorg", func(r *ghttp.Request) {
		routers.MethodCallWithVersionStrategy(r, map[string]interface{}{
			"1.0.0": c.ListOrg,
		}, defaultVersion, routers.DemoteStrategy)
	})
}

func (c *cRole) Add(r *ghttp.Request) *response.JsonResponse {
	return RoleService.Add(r, c.Req)
}

func (c *cRole) Update(r *ghttp.Request) *response.JsonResponse {
	if c.Req.UpdateReq != nil {
		if err := r.Parse(c.Req.UpdateReq); err != nil {
			return response.FailByRequestMessage(r, err.Error())
		}
	}
	if err := c.CheckId(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return RoleService.Update(r, c.Req)
}

func (c *cRole) Info(r *ghttp.Request) *response.JsonResponse {
	if err := c.CheckId(r); err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return RoleService.Info(r.GetCtx(), c.Req)
}

// 属于 组织人员 的角色
func (c *cRole) ListOrg(r *ghttp.Request) *response.JsonResponse {
	return RoleService.List(r, c.Req)
}
